import userModel from '../../model/user'
import $ from '../../utils/tool'
const db = wx.cloud.database()
const _ = db.command
const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    hidedFromWorldList: false,
    friendList: []
  },
  onLoad() {
    let hasUserInfo = $.storage.get('hasUserInfo')
    let userInfo = $.storage.get('userInfo')
    let openid = $.storage.get('openid')
    if( hasUserInfo == true ) {
      getApp().globalData.hasUserInfo = hasUserInfo
      getApp().globalData.userInfo = userInfo
      getApp().globalData.openid = openid
      this.setData({hasUserInfo, userInfo})
    }
  },
  onShow() {
    if( this.data.hasUserInfo == true ) {
      // 获取好友请求信息
      this.getFriendRequest()
    }
  },
  // 获取用户信息userinfo
  async getUserProfile() {
    let hasUserInfo = $.storage.get('hasUserInfo')
    if (hasUserInfo == true) return
    wx.getUserProfile({
      desc: '将用于好友排名显示',
      success: res => {
        let userInfo = res.userInfo
        this.setData({
          userInfo: userInfo,
          hasUserInfo: true
        })
        // 改变全局变量
        getApp().globalData.hasUserInfo = true
        getApp().globalData.userInfo = userInfo
        userInfo = userModel.updateUserFocus(userInfo) //传focus内容
        this.uploadInfo(userInfo)
        // 获取好友请求信息
        this.getFriendRequest()
      },
      fail: err => {
        console.log('用户拒绝登录', err)
      }
    })
  },

  async uploadInfo(userInfo) {
    const openid = app.globalData.openid
    if (!openid) {      // 第一次登录
      await userModel.getOwnInfo(userInfo).then(res => {
        console.log('!openid, getOwnInfo', res)
        $.storage.set('openid', res._openid)
        this.setData({ userInfo: res })
        // 放入缓存，保存登录状态
        $.storage.set('hasUserInfo', true)
        $.storage.set('userInfo', res)
      })
    }
    console.log('上传云成功') 
  },

  // 获取好友请求
  getFriendRequest() {
    db.collection('request').where({
      userId: app.globalData.userInfo._id
    }).watch({
      onChange: snapshot => {
        if(snapshot.docChanges.length) {
          let list = snapshot.docChanges[0].doc.list
          this.setData({friendList: list})
          if (list.length) {
            getApp().globalData.requestUserInfo = list
          }else {
            getApp().globalData.requestUserInfo = []
          }
        }
      },
      onError: err => {
        console.log(err)
      }
    })
  },

  switchFriend() {
    wx.showToast({
      title: '即将跳转到好友管理界面',
      icon: 'none',
      success() {
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/friend/friend?index=1',
          })
        }, 1500)
      }  
    })
  }

})
